package com.prince.web.service.impl;

import com.prince.bean.CommonWebResponse;
import com.prince.bean.ResultParams;
import com.prince.bean.WebCode;
import com.prince.constant.Constants;
import com.prince.mapper.LimitsMapper;
import com.prince.mapper.RoleLimitMapper;
import com.prince.mapper.UserMapper;
import com.prince.mapper.x.UserLimitsMapper;
import com.prince.model.Limits;
import com.prince.model.LimitsExample;
import com.prince.model.LimitsExample.Criteria;
import com.prince.model.RoleLimit;
import com.prince.model.User;
import com.prince.util.ListUtils;
import com.prince.util.MapUtil;
import com.prince.util.StringUtil;
import com.prince.web.base.BaseService;
import com.prince.web.service.LimitsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 权限
 * 
 * @author WangPeixi
 *
 */
@Service
public class LimitServiceImpl extends BaseService implements LimitsService {

	@Resource
	private LimitsMapper limitsMapper; // 权限

	@Resource
	private UserLimitsMapper userLimitsMapper; // 用户权限

	@Resource
	private UserMapper userMapper; // 用户表

	@Resource
	private RoleLimitMapper roleLimitMapper; // 权限中间表

//	@Resource
//	private LimitsCache limitsCache; // redis 用户权限
	/*
	 * 根据用户id查询菜单
	 * 
	 * @see com.prince.service.LimitsService#findLimitsByUserId(java.util.Map)
	 */

	@Override
	public Map<String, Object> findLimitsByUserId(User user) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		//判断用户是否为空
		if (null == user) {
			logger.debug("[ LimitServiceImpl ] findLimitsByUserId id为空  查询菜单失败！");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//执行查询
		List<Limits> list = userLimitsMapper.selectLimitsByUserId(user.getId());
		Integer warningLimits = userLimitsMapper.selectWarningLimits(user.getId());
		//把结果放入response域中
		response.put("data", list);
		response.put("warning", warningLimits);
		return response.toHashMap();
	}

	/*
	 * 查询所有菜单
	 * 
	 * @see com.prince.service.LimitsService#findLimitsAll()
	 */
	@Override
	public Map<String, Object> findLimitsAll(User user) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		logger.info("[ LimitServiceImpl ] findLimitsAll  查询所有菜单==");
		//创建查询
		LimitsExample example = new LimitsExample();
		example.createCriteria().andDelEqualTo(Constants.YES);
		List<Limits> list = null;
		//通过角色查询
		if(!StringUtil.stringEquals(Constants.ADMIN,user.getBelongType())) {
			if(null !=user.getParentId() && Constants.ZERO != user.getParentId()) {
				//员工查上级手机号   管理员查自己手机号
				if(StringUtil.stringEquals(Constants.STAFF, user.getBelongType())){
					list =	userLimitsMapper.selectLimitsByUserIdAndParentId(user.getParentId());
				}else {
					list =	userLimitsMapper.selectLimitsByUserIdAndParentId(user.getId());
				}
			}
		}else {
			list = limitsMapper.selectByExample(example);
		}
		
		
		//判断是否为空
		if (null == list) {
			logger.debug("[ LimitServiceImpl ] findLimitsAll  查询所有菜单失败！");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		response.put("data", list);
		logger.info("[ LimitServiceImpl ] findLimitsAll 查询所有菜单 ："+ response.toHashMap());
		return response.toHashMap();
	}

	@Override
	public Map<String, Object> findCodeByAddr(Limits limits) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		LimitsExample limitsExample = new LimitsExample();
		Criteria createCriteria = limitsExample.createCriteria();
		createCriteria.andAddrEqualTo(limits.getAddr());
		List<Limits> limit = limitsMapper.selectByExample(limitsExample);
		response.put("code",limit.get(0).getCode().toString());
		return response.toHashMap();

	}

	/*
	 * 根据parentCode查询
	 * 
	 * @see com.prince.service.LimitsService#findLimitsByParentCode(java.lang.String)
	 */
	@Override
	public Map<String, Object> findLimitsByParentCode(Limits limits) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		logger.info("[ LimitServiceImpl ] findLimitsByParentCode  ===根据parentCode查询开始===");
		//判断是否为空
		if (null == limits) {
			logger.debug("根据parentCode查询失败！");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
        //创建查询
		LimitsExample limitsExample = new LimitsExample();
		Criteria createCriteria = limitsExample.createCriteria();
		createCriteria.andDelEqualTo(Constants.YES);
		//添加条件
		if (null != limits.getParentCode()) {
			createCriteria.andParentCodeEqualTo(limits.getParentCode());
		}
		if (null != limits.getCode() ) {
			createCriteria.andCodeEqualTo(limits.getCode());
		}

		limitsExample.setOrderByClause("sort asc");
         //执行查询
		List<Limits> list = limitsMapper.selectByExample(limitsExample);
		
		response.put("data", list);
		logger.info("[ LimitServiceImpl ] findLimitsByParentCode  ===根据parentCode查询结束 :" + response.toHashMap());
		return response.toHashMap();
	}

	/*
	 * 添加权限
	 * 
	 * @see com.prince.service.LimitsService#addLimits(com.prince.model.Limits)
	 */
	@Override
	@Transactional
	public synchronized Map<String, Object> addLimits(Limits limits, User user) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		logger.info("[ LimitServiceImpl ] addLimits  ===添加权限===");
		limits.setCreated(new Date());
		limits.setDel(Constants.YES);
		Integer max = userLimitsMapper.selectMaxCode();
		logger.info("[ LimitServiceImpl ] addLimits 最大id : " + max);
		max++;
		limits.setCode(max);

		logger.info("[ LimitServiceImpl ] addLimits ParentCode : " + limits.getParentCode());
		//判断是否为空，如果为空设置parentcode为0
		if (null == limits.getParentCode()) {
			limits.setParentCode(0);
		}
		// 设置机构号
		int i = limitsMapper.insertSelective(limits);
		if (!(i > 0)) {
			logger.debug("[ LimitServiceImpl ] addLimits 添加权限失败！");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}

		// 管理员添加权限
		User u = userMapper.selectByPrimaryKey(Constants.ONE);
		if (u !=null) {
			Integer roleId = u.getRoleId();
			// 封装权限中间表对象
			RoleLimit roleLimit = new RoleLimit();
			roleLimit.setCreated(new Date());
			roleLimit.setRoleId(roleId);
			roleLimit.setLimitId(limits.getId());
			logger.info("roleid = " + roleId + "   limitsId  =" + limits.getId());
			// 插入中间表
			roleLimitMapper.insertSelective(roleLimit);
		}
		logger.info("[ LimitServiceImpl ] addLimits  ===添加权限结束：" + response.toHashMap());
		return response.toHashMap();
	}

	/*
	 * 根据id查询权限
	 * 
	 * @see com.prince.service.LimitsService#findLimitsById(java.lang.Integer)
	 */
	@Override
	public Map<String, Object> findLimitsById(Integer id) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		logger.info("[ LimitServiceImpl ] findLimitsById  ===根据id查询权限===");
		if (null == id) {
			logger.debug("根据id查询权限  id 为空！");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//执行查询
		Limits limits = limitsMapper.selectByPrimaryKey(id);
		response.put("data", limits);
		logger.info("[ LimitServiceImpl ] findLimitsById  ===根据id查询权限结束：" + response.toHashMap());
		return response.toHashMap();
	}

	/*
	 * 更新权限
	 * 
	 * @see com.prince.service.LimitsService#updateLimits(com.prince.model.Limits)
	 */
	@Override
	public Map<String, Object> updateLimits(Limits limits) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		logger.info("[ LimitServiceImpl ] updateLimits  ===更新权限开始===");
		//执行更新
		int i = limitsMapper.updateByPrimaryKeySelective(limits);
		if (!(i > 0)) {
			logger.debug("更新权限失败！");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		logger.info("[ LimitServiceImpl ] updateLimits  ===更新权限结束：" + response.toHashMap());
		return response.toHashMap();
	}

	/*
	 * 通过userId、parentCode 查询 按钮权限
	 * 
	 * @see
	 * com.prince.service.back.service.LimitsService#selectLimitsByUserIdAndParentCode(
	 * com.prince.model.Limits, com.prince.model.User)
	 */
	@Override
	public Map<String, Object> selectLimitsByUserIdAndParentCode(Map<String, Object> params, User user) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();// parentCode=15
		if (!MapUtil.isNotEmpty(params, "parentCode")) {
			logger.debug("父节点为空 没有按钮权限！");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		params.put("userId", user.getId());
		params.put("type", "button");
		//执行查询
		List<Limits> list = userLimitsMapper.selectLimitsByUserIdAndParentCode(params);
		if (ListUtils.isEmpty(list)) {
			logger.info("用户" + user.getLoginName() + "没有父节点为" + params.get("parentCode") + "按钮权限");
		}
		response.put("data", list);
		return response.toHashMap();
		
	}

	/*
	 * 页面 js 过滤
	 * 
	 * @see
	 * com.prince.service.back.service.LimitsService#limitsFilter(java.lang.String,
	 * com.prince.model.User)
	 */
	@Override
	public boolean limitsFilter(String url, User user) {
		logger.info("查询权限-----------" + url + "-----------");
		if (url.endsWith(".html") || url.endsWith(".js")) {
			if (url.contains("add") || url.contains("update")) {
				url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
			} else {
				return true;
			}
		}
		boolean flag =false;
		// redis 查询
//		String result = limitsCache.get(user.getRoleId().toString());	
//		String result = null;
//		if (StringUtil.isNotEmpty(result) && result.length() > 2) {
//			result = result.substring(1, result.length()-1);
//			String[] split = result.split(",");
//			for (String str : split) {
//				if (str.trim().contains(url.trim())) {
//					flag=true;
//					break;
//				} 
//			}
//			
//		}else {
			// redis中没有 数据库查询
			List<String> limitList = userLimitsMapper.selectRoleIdByAddr(user.getRoleId());
			if (ListUtils.isNotEmpty(limitList)) {
				// 放入redis
//				logger.info("添加redis :" + limitList.toString());
//				if (null == result || result.length() < 3) {
//					limitsCache.set(user.getRoleId().toString(), limitList.toString());
//				}
				
				for (String str : limitList) {
					if (str.trim().contains(url.trim())) {
						flag = true;
						break;
					} 
				}
			}
//		}
		return flag;
	}

	/*
	 * 删除权限
	 * 
	 * @see
	 * com.prince.service.back.service.LimitsService#delLimits(com.prince.model.Limits)
	 */
	@Override
	public Map<String, Object> delLimits(Limits limits) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		logger.info("[ LimitServiceImpl ] delLimits  ===删除权限开始===");
		//逻辑删除
		limits.setDel(Constants.NO);
		int i = limitsMapper.updateByPrimaryKeySelective(limits);
		if (!(i > 0)) {
			logger.info("[ LimitsService ] delLimits 删除权限失败！");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		logger.info("[ LimitServiceImpl ] delLimits  ===删除权限结束："+response.toHashMap());
		return response.toHashMap();
	}
}
